package com.quick.proxy.core.handler;

import com.quick.proxy.core.Match;
import com.quick.proxy.core.ProxyMessage;
import com.quick.proxy.core.ProxyMessageHandler;
import com.quick.proxy.core.utils.ByteUtils;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description: 协议处置处理程序
 * Author: 吃素不吃肉
 * Date: 2023/7/4
 *
 * @author 吃素不吃肉
 */
@Slf4j
@Sharable
@Component
public class ProtocolDisposeHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg != null) {
            ProxyMessage proxyMessage = (ProxyMessage) msg;
            Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Match.class);
            for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
                Match annotation = entry.getValue().getClass().getAnnotation(Match.class);
                if (proxyMessage.getCmdType().equals(ByteUtils.intToHex(annotation.value(), 1))) {
                    Object value = entry.getValue();
                    if (value instanceof ProxyMessageHandler) {
                        ((ProxyMessageHandler) value).cmdResponse(ctx, proxyMessage);
                    }
                }
            }
        }
    }
}
